package com.itheima.web.controller;

import com.itheima.domain.User;
import com.itheima.service.ModuleService;
import com.itheima.service.UserService;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/authentication/*")
public class AuthenticationServlet extends BaseServlet {

    /**
     * 处理用户登录的请求
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UserService userService = ac.getBean("userService", UserService.class);
        ModuleService moduleService = ac.getBean("moduleService", ModuleService.class);
        //1 获取请求参数
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        //2 调用service层方法进行登录，得到User对象
        User user=userService.login(email,password);
        //3 判断是否登录成功，页面跳转
        if(user!=null){
            //登录成功
            //将用户信息保存到session
            request.getSession().setAttribute("user",user);

            //登录成功之后保存用户的操作权限，也就是用户可以访问后台哪些模块的CRUD路径
            List<String> curls=moduleService.findPermissionByUserId(user.getId());
            request.getSession().setAttribute("curls",curls);

            //获取要跳转的路径，如果有就往这个路径中跳转
            String sendRedirect = (String) request.getSession().getAttribute("sendRedirect");
            //如果没有就默认跳转到/pages/main.html
            if(StringUtils.isBlank(sendRedirect)){
                //跳转到/pages/main.html
                response.sendRedirect(request.getContextPath()+"/pages/main.html");
            }else {
                response.sendRedirect(sendRedirect);
            }
        }else{
            //登录失败
            response.sendRedirect(request.getContextPath()+"/login.html");
        }
    }
    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //直接清空session
        request.getSession().invalidate();
        //页面跳转
        response.sendRedirect(request.getContextPath()+"/login.html");
    }
}
